package com.tina.listener;

import com.alibaba.fastjson.JSON;
import com.tina.constant.ShopCode;
import com.tina.entity.Orders;
import com.tina.service.IOrdersService;
import com.tina.util.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;


@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.pay.topic}", consumerGroup = "${mq.pay.consumer.group.name}", messageModel = MessageModel.BROADCASTING)
public class PaymentListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private MailUtil mailUtil;

    @Override
    public void onMessage(MessageExt messageExt) {

        log.info("接收到支付成功消息");

        try {
            String body = new String(messageExt.getBody(), "UTF-8");
            log.info("body->{}", body);
            Orders orders = JSON.parseObject(body, Orders.class);
            Orders flowers = new Orders();
            flowers.setOrderId(orders.getOrderId());
            flowers.setStatus(ShopCode.SHOP_ORDER_PAY_STATUS_IS_PAY.getCode());
            ordersService.editOrders(flowers);
            log.info("更改订单支付状态为已支付成功");
            Context context = new Context();
            context.setVariable("productName", orders.getTitle());
            context.setVariable("productPrice", orders.getSellPrice());
            context.setVariable("productImg", orders.getCover());
            mailUtil.sendMail(orders.getMail(), "下单成功", "mail", context);

        } catch (Exception e) {
            log.info("更改订单支付状态为已支付失败");
            e.printStackTrace();
        }

    }
}
